package com.gmail.blackdog1987.carcare;

import java.lang.reflect.Method;
import java.util.HashMap;

import android.app.Application;
import android.util.Log;

import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.PushService;
import com.gmail.blackdog1987.carcare.db.DbHelper;
import com.gmail.blackdog1987.carcare.util.LogUtil;
import com.gmail.blackdog1987.carcare.util.NetworkUtils;

/**
 * 
 * @author 董国超
 * 
 */
public class App extends Application {

	/** Application实例 */
	private static App sInstance;
	/** 网络助手实例 */
	private static NetworkUtils sNetworkUtils;
	/** 数据库助手实例 */
	private static DbHelper sDbHelper;
	
	 private static HashMap<String, String> userNameCache = new HashMap<String, String>();

	@Override
	protected void finalize() throws Throwable {
		if (sDbHelper != null && sDbHelper.isOpen()) {
			sDbHelper.close();
		}
		sDbHelper = null;
		sInstance = null;
		super.finalize();
	}

	/**
	 * 获取数据库助手实例。
	 * 
	 * @return 数据库助手实例。
	 */
	public static DbHelper getDbHelper() {
		if (sDbHelper == null) {
			sDbHelper = DbHelper.getDefault(getInstance());
			sDbHelper.open();
		}
		return sDbHelper;
	}

	@Override
	public void onCreate() {
		sInstance = this;
		super.onCreate();

		// init avos congif

	    try {
	      Class<?> avosclass = Class.forName("com.avos.avoscloud.AVOSCloud");
	      Method enableLogMethod = avosclass.getDeclaredMethod("showInternalDebugLog", boolean.class);
	      enableLogMethod.setAccessible(true);
	      enableLogMethod.invoke(avosclass, true);
	      com.avos.avoscloud.LogUtil.avlog.i("successed enable avoscloud logs");
	    } catch (Exception e) {
	    	com.avos.avoscloud.LogUtil.avlog.i("failed enable avoscloud logs");
	    }
		
		LogUtil.setLogLevel(Log.ASSERT);
		// LogUtil.setLogLevel(Log.ASSERT); // 设置LogCat输出等级
		LogUtil.setLogLevel(Log.DEBUG); // 设置LogCat输出等级
		getDbHelper();
	}

	/**
	 * 获取Application实例。
	 * 
	 * @return Application实例。
	 */
	public static App getInstance() {
		return sInstance;
	}

	/**
	 * 获取网络助手实例。
	 * 
	 * @return 网络助手实例。
	 */
	public static NetworkUtils getNetworkHelper() {
		if (sNetworkUtils == null) {
			sNetworkUtils = new NetworkUtils();
		}
		return sNetworkUtils;
	}

	public static String lookupname(String peerId) {
		return userNameCache.get(peerId);
	}

	public static void registerLocalNameCache(String peerId, String name) {
		userNameCache.put(peerId, name);
	}
}
